<template>
  <div class="meal-record-wrapper">
    <el-main>
      <div v-if="viewerName" class="viewer-tip">
        当前正在查看 <strong>{{ viewerName }}</strong> 的订餐记录
      </div>
      <!-- 第一行：日期 + 时间 + 搜索 -->
      <el-form :inline="true" class="filter-form first-line">
        <el-form-item>
          <el-select
              v-model="filters.mealTime"
              placeholder="用餐时间"
              clearable
              @change="onSearch"
              style="width: 120px;"
          >
          <el-option label="全部" value="" />
          <el-option label="早" value="早" />
          <el-option label="午" value="午" />
          <el-option label="晚" value="晚" />
        </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
              v-model="filters.startDay"
              type="date"
              placeholder="起始日期"
              clearable
              value-format="YYYY-MM-DD"
              @change="onSearch"
              style="width: 140px"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
              v-model="filters.endDay"
              type="date"
              placeholder="结束日期"
              clearable
              value-format="YYYY-MM-DD"
              :picker-options="endPickerOptions"
              @change="onSearch"
              style="width: 140px"
          />
        </el-form-item>

      </el-form>

      <!-- 第二行：食物种类 + 操作按钮 -->
      <el-form :inline="true" class="filter-form second-line">
        <el-form-item>
          <el-select
              v-model="filters.foodType"
              placeholder="食物种类"
              clearable
              @change="onSearch"
              style="width: 140px"
          >
            <el-option
                v-for="type in FOOD_TYPES"
                :key="type"
                :label="type"
                :value="type === '全部' ? '' : type"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="keyword-item">
          <el-input
              v-model="filters.keyword"
              placeholder="按食物名称搜索"
              clearable
              @clear="onSearch"
              @keyup.enter="onSearch"
              style="width:190px;"
          >
            <template #append>
              <el-button @click="onSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <!-- 这里加个空项撑开中间，再用 margin-left: auto -->
        <el-form-item class="action-buttons">
          <el-button type="success" @click="openAddDialog">新增订餐记录</el-button>
          <el-button type="warning" @click="goBack">返回用户列表</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
          v-if="list.length"
          :data="list"
          border
          stripe
          class="meal-table"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="mealCalendarDay" label="用餐日期"/>
        <el-table-column prop="mealCalendarTime" label="用餐时间"/>
        <el-table-column prop="foodType" label="食物种类" />
        <el-table-column prop="foodName" label="食物名称" />
        <el-table-column prop="count" label="订餐份数" />
        <el-table-column label="订单状态" width="110">
        <template #default="{ row }">
          <el-tag :type="row.statusColor">
            {{ row.statusLabel }}
          </el-tag>
        </template>
      </el-table-column>


        <el-table-column label="操作">
          <template #default="{ row }">

            <el-button
                size="small"
                type="primary"
                @click="handleEdit(row)"
                v-if="row.statusLabel === '未完成'"
            >
              修改
            </el-button>

            <el-button
                size="small"
                type="danger"
                @click="onRemove(row.mealRecordId)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-else class="empty">暂无订餐记录</div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="paginationMain.total"
            v-model:current-page="paginationMain.current"
            v-model:page-size="paginationMain.size"
            :page-sizes="[5, 10, 20, 50]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
        />
      </div>

      <!-- 新增订餐对话框 -->
      <el-dialog
          v-model="addDialog.visible"
          title="新增订餐记录"
          width="800px"
          @open="fetchListAdd"
      >
        <el-form :inline="true" class="filter-form first-line">
          <el-select
              v-model="filtersAdd.mealCalendarDate"
              placeholder="日期"
              clearable
              style="width: 140px; margin-right: 12px"
              @change="onSearchAdd"
          >
            <el-option
                v-for="opt in dateOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
          <el-select
              v-model="filtersAdd.mealCalendarTime"
              placeholder="时段"
              clearable
              style="width: 120px; margin-right: 12px"
              @change="onSearchAdd"
          >
            <el-option
                v-for="opt in timeOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
        </el-form>
        <el-form :inline="true" class="filter-form second-line">
        <el-select
            v-model="filtersAdd.foodType"
            placeholder="食物类型"
            clearable
            style="width: 180px; margin-right: 12px;margin-top: 12px;margin-bottom: 12px"
            @change="onSearchAdd"
        >
          <el-option
              v-for="type in FOOD_TYPES"
              :key="type"
              :label="type"
              :value="type === '全部' ? '' : type"
          />
        </el-select>
        <el-input
            v-model="filtersAdd.foodName"
            placeholder="食物名称"
            clearable
            style="width: 180px; margin-right: 12px;margin-top: 12px;margin-bottom: 12px"
            @clear="onSearchAdd"
            @keyup.enter="onSearchAdd"
        />
        <el-button type="primary" @click="onSearchAdd">
          <el-icon>
            <Search/>
          </el-icon>
        </el-button>
        </el-form>
        <el-table
            v-if="tableData.length"
            :data="tableData"
            border
            stripe
            style="width: 100%; margin-top: 16px"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="mealCalendarDate" label="日期" width="65"/>
          <el-table-column prop="mealCalendarDay" label="实际日期" />
          <el-table-column prop="mealCalendarTime" label="时段" width="65" />
          <el-table-column prop="foodType" label="食物类型" />
          <el-table-column prop="foodName" label="食物名称" />

          <!-- 订餐数量列 -->
          <el-table-column label="订餐数量">
            <template v-slot="scope">
              <el-input-number
                  v-model="scope.row.count"
                  :min="0"
                  :step="1"
                  size="small"
                  @input="handleCountChange(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top:16px; text-align:right;">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              v-model:current-page="pagination.current"
              v-model:page-size="pagination.size"
              :page-sizes="[5,10,20,50]"
              @current-change="handlePageChangeAdd"
              @size-change="handleSizeChangeAdd"
          />
        </div>

          <template #footer>
            <el-button @click="addDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="submitAdd" :loading="addDialog.loading">提交</el-button>
          </template>
      </el-dialog>

      <!-- 修改对话框 -->
      <el-dialog
          title="修改订餐份数"
          v-model="editDialog.visible"
          width="30%"
      >
        <el-form
            ref="editForm"
            :model="editRecord"
            label-width="120px"
        >
          <!-- 只读信息展示 -->
          <el-form-item label="客户姓名">
            <el-input v-model="editRecord.clientName" disabled />
          </el-form-item>
          <el-form-item label="餐点日期">
            <el-input v-model="editRecord.mealCalendarDate" disabled />
          </el-form-item>
          <el-form-item label="餐点时段">
            <el-input v-model="editRecord.mealCalendarTime" disabled />
          </el-form-item>
          <el-form-item label="食物类型">
            <el-input v-model="editRecord.foodType" disabled />
          </el-form-item>
          <el-form-item label="食物名称">
            <el-input v-model="editRecord.foodName" disabled />
          </el-form-item>

          <!-- 可编辑的订餐份数 -->
          <el-form-item
              label="订餐份数"
              prop="count"
              :rules="[
          { required: true, message: '请输入订餐份数' },
          { type: 'number', min: 1, message: '份数不能小于1' }
        ]"
          >
            <el-input-number
                v-model="editRecord.count"
                :min="1"
                controls-position="right"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitEdit"
              :loading="editDialog.loading"
          >确定</el-button>
        </template>
      </el-dialog>

    </el-main>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed, watch, onUnmounted} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {listByClient, deleteMealRecord, createMealRecord, updateMealRecord} from '@/api/apiList/mealRecord'
import {listMealCalendars} from "@/api/apiList/mealCalendar";
const dateMap = ref({});
const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
const route = useRoute()
const router = useRouter()
const clientId = Number(route.params.clientId)
const selectedRecords = ref([])
const clientName = ref('')
const filters = reactive({
  startDay: null,
  endDay: null,
  foodType: '',
  mealTime: '',
  keyword: '',
  count: 0
})
const filtersAdd = reactive({
  mealCalendarId:0,
  mealCalendarTime: '',
  foodName: '',
  foodType: '',
  mealCalendarDate:'',
  count: 0
})
const dateOptions = [
  {label: '全部', value: ''},
  {label: '周一', value: '周一'},
  {label: '周二', value: '周二'},
  {label: '周三', value: '周三'},
  {label: '周四', value: '周四'},
  {label: '周五', value: '周五'},
  {label: '周六', value: '周六'},
  {label: '周日', value: '周日'}
]
const timeOptions = [
  {label: '全部', value: ''},
  {label: '早', value: '早'},
  {label: '午', value: '午'},
  {label: '晚', value: '晚'}
]
const FOOD_TYPES = [
  '全部',
  '蔬菜',
  '水果',
  '肉类',
  '海鲜',
  '蛋类',
  '奶制品',
  '豆制品',
  '主食',
  '饮料',
  '其他'
]
const paginationMain = reactive({ current: 1, size: 10, total: 0 }) // 主表格分页
const paginationAdd = reactive({ current: 1, size: 10, total: 0 })  // 弹窗分页

const viewerName = ref('')
const list = ref([])
const tableData = ref([])
const pagination = reactive({ current: 1, size: 10, total: 0 })
const currentDate = new Date()
async function fetchList() {
  if (!clientId) return ElMessage.error('缺少 clientId')
  const params = {
    clientId,
    page: paginationMain.current,
    size: paginationMain.size,
    startDay: filters.startDay ? filters.startDay.replace(/\//g, '-') : undefined,
    endDay:   filters.endDay   ? filters.endDay.replace(/\//g, '-')   : undefined,
    foodType: filters.foodType  || undefined,
    mealTime: filters.mealTime  || undefined,
    foodName: filters.keyword   || undefined,
    count:filters.count || undefined
  }
  try {
    const pageData = await listByClient(params)
    list.value = pageData.records || []
    list.value = pageData.records.map(r => {
      const status = getOrderStatus(r);
      return {
        ...r,
        statusLabel: status.label,
        statusColor: status.color
      };
    });


    paginationMain.total = pageData.total || 0
    if (list.value.length) {
      clientName.value = list.value[0].clientName
    }
  } catch (err) {
    const msg = err.response?.data?.message || err.message || '获取订餐记录失败'
    ElMessage.error(msg)
  }
}
// 计算本周日期（从今天到周日）
const editDialog = reactive({
  visible: false,
  loading: false
});

const editRecord = ref({
  mealRecordId: null,
  clientId: null,
  clientName: '',
  mealCalendarDate: '',
  mealCalendarTime: '',
  foodType: '',
  foodName: '',
  count: 0
});

const editForm = ref(null);

// 处理修改操作
function handleEdit(row) {
  // 填充编辑表单数据
  editRecord.value = {
    ...row,
    // 确保count是数字类型
    count: Number(row.count)
  };
  editDialog.visible = true;
}
function getOrderStatus(record) {
  const now = new Date();
  const todayStr = now.toISOString().split('T')[0];
  const today = new Date(todayStr); // 去掉时分秒
  const mealDate = new Date(record.mealCalendarDay);

  const status = {
    label: '',
    color: ''  // 用于后续 tag 显示颜色
  };

  if (mealDate < today) {
    status.label = '已完成';
    status.color = 'success';
    return status;
  }

  if (mealDate > today) {
    status.label = '未完成';
    status.color = 'info';
    return status;
  }

  // === 如果是当天 ===
  const deadline = new Date(record.mealCalendarDay);
  switch (record.mealCalendarTime) {
    case '早':
      deadline.setHours(6, 0, 0, 0);
      break;
    case '午':
      deadline.setHours(10, 0, 0, 0);
      break;
    case '晚':
      deadline.setHours(16, 0, 0, 0);
      break;
    default:
      status.label = '未知';
      status.color = 'warning';
      return status;
  }

  if (now < deadline) {
    status.label = '进行中';
    status.color = 'warning';
  } else {
    status.label = '已完成';
    status.color = 'success';
  }

  return status;
}


// 提交修改
async function submitEdit() {
  try {
    // 表单验证
    if (!editForm.value) {
      console.error('表单引用未初始化');
      ElMessage.error('表单初始化失败，请重试');
      return;
    }

    // 打印调试信息
    console.log('开始修改记录 ID:', editRecord.value.mealRecordId);
    console.log('修改数量:', editRecord.value.count);

    editDialog.loading = true;

    // 检查 count 是否为有效数字
    if (isNaN(editRecord.value.count) || editRecord.value.count <= 0) {
      console.error('无效的数量:', editRecord.value.count);
      ElMessage.error('请提供有效的订餐份数');
      return;
    }

    // 打印请求参数
    const params = {
      mealRecordId: editRecord.value.mealRecordId,
      count: editRecord.value.count
    };
    console.log('请求参数:', JSON.stringify(params));

    // 调用后端接口
    const response = await updateMealRecord(params);
    fetchList()
    editDialog.visible = false;
  } catch (error) {
    // 捕获所有异常并详细输出
    console.error('修改出错:', error);

  } finally {
    editDialog.loading = false;
  }
}
function calcWeekDates() {
  const today = new Date()
  const day = today.getDay() || 7  // Sunday = 7
  const dates = []
  for (let i = 0; i <= 7 - day; i++) {
    const d = new Date(today)
    d.setDate(d.getDate() + i)
    dates.push(d.toISOString().slice(0, 10))
  }
  return dates
}
// 计算本周日期映射
function getWeekDatesMap() {
  const today = new Date();
  // 把 JS getDay()（0=周日…6=周六）转换成 ISO 周几 1-7
  const isoDayOfWeek = today.getDay() === 0 ? 7 : today.getDay();
  const map = {};
  // ISO 周的 label 数组，索引 1-7 有效
  const weekDaysISO = [null, '周一', '周二', '周三', '周四', '周五', '周六', '周日'];

  for (let i = isoDayOfWeek; i <= 7; i++) {
    // 计算相对于今天 + (i - isoDayOfWeek) 天
    const d = new Date(today);
    d.setDate(today.getDate() + (i - isoDayOfWeek));
    const dateStr = d.toISOString().split('T')[0];      // 'YYYY-MM-DD'
    map[weekDaysISO[i]] = dateStr;                      // map['周三'] = '2025-07-09'
  }

  return map;
}
// 弹窗相关状态
const addDialog = reactive({
  visible: false,
  loading: false,
  calendar: []  // 每项会包含：mealCalendarId, mealCalendarDate, mealCalendarTime, foodName, foodType, count
})

function openAddDialog() {
  // 计算本周日期映射
  dateMap.value = getWeekDatesMap();

  // 重置过滤条件和分页
  Object.assign(filtersAdd, {
    mealCalendarId: 0,
    mealCalendarTime: '',
    foodName: '',
    foodType: '',
    mealCalendarDate: '',
    count: 0
  });

  selectedRecords.value = []; // 清空之前的选择
  addDialog.visible = true;
}
function handleCountChange(row) {
  console.log(`Updated count for ${row.foodName}: ${row.count}`)
}
// 拉取列表（含分页）
async function fetchListAdd() {
  try {
    const params = {
      ...filtersAdd,
      page: pagination.current,
      size: pagination.size
    };
    const pageData = await listMealCalendars(params);

    if (!pageData || !pageData.records || !Array.isArray(pageData.records)) {
      ElMessage.error('没有找到膳食日历记录');
      return;
    }

    // 先做一次后台返回的 records 过滤
    const filtered = pageData.records
        .filter(r => r.mealCalendarStatus === '启用')
        .filter(r => dateMap.value.hasOwnProperty(r.mealCalendarDate))
        .map(item => ({
          ...item,
          mealCalendarDay: dateMap.value[item.mealCalendarDate],
          count: 0
        }));

    // 把过滤后的列表赋给 tableData
    tableData.value = filtered;

    // **关键**：把 pagination.total 更新为过滤后的长度
    pagination.total = filtered.length;
  } catch (err) {
    ElMessage.error('获取失败');
  }
}


function onSearchAdd() {
  console.log('Searching with current filters:', filtersAdd)
  pagination.current = 1  // Reset to the first page on new search
  fetchListAdd()  // Call fetch function to get the filtered data
}

function handleSelectionChange(selection) {
  selectedRecords.value = selection;
}
// 提交新增订餐记录
async function submitAdd() {
  const toAdd = selectedRecords.value.filter(row => row.count > 0)
  if (!toAdd.length) {
    ElMessage.warning('您还没有进行订餐哦')
    return
  }

  addDialog.loading = true
  try {
    await Promise.all(
        toAdd.map(record => createMealRecord({
          mealCalendarId:record.mealCalendarId,
          clientId,
          count: record.count,
          mealCalendarDay: record.mealCalendarDay
        }))
    )
    ElMessage.success('新增成功')
    addDialog.visible = false
  } catch (e) {
    console.error(e)
    ElMessage.error('新增失败')
  } finally {
    addDialog.loading = false
  }
  fetchList()
}
// --- 新增 watch：选结束日期时，若 end<=start，清空 endDay 并提示 ---
watch(() => filters.endDay, (newEnd) => {
  if (newEnd && filters.startDay) {
    if (new Date(newEnd) <= new Date(filters.startDay)) {
      ElMessage.error('结束日期必须晚于起始日期，已清空错误选择')
      filters.endDay = null
    }
  }
})

// --- 同理，watch startDay，当 start>=end 时清空 startDay ---
watch(() => filters.startDay, (newStart) => {
  if (newStart && filters.endDay) {
    if (new Date(newStart) >= new Date(filters.endDay)) {
      ElMessage.error('起始日期必须早于结束日期，已清空错误选择')
      filters.startDay = null
    }
  }
})
function onSearch() {
  // 校验：如果同时选了 startDay 和 endDay，且 endDay <= startDay，则报错
  if (filters.startDay && filters.endDay) {
    const start = new Date(filters.startDay)
    const end   = new Date(filters.endDay)
    if (end <= start) {
      ElMessage.error('结束日期必须晚于起始日期')
      return
    }
  }
  pagination.current = 1
  fetchList()
}
function handlePageChangeAdd(page) {
  pagination.current = page
  fetchListAdd()
}

function handleSizeChangeAdd(size) {
  pagination.size = size
  pagination.current = 1
  fetchList()
}
function handlePageChange(page) {
  paginationMain.current = page;
  fetchList();
}
function handleSizeChange(size) {
  paginationMain.size = size;
  paginationMain.current = 1;
  fetchList();
}

// 结束日期的picker-options：禁选 <= startDay
const endPickerOptions = computed(() => ({
  disabledDate(date) {
    if (!filters.startDay) return false
    // date 为 JS Date 对象，filters.startDay 格式 "YYYY-MM-DD"
    const min = new Date(filters.startDay)
    return date <= min
  }
}))
async function onRemove(id) {
  try {
    await ElMessageBox.confirm('确认移除此订餐记录？', '提示', {type: 'warning'})
    await deleteMealRecord(id)
    ElMessage.success('移除成功')
    fetchList()
  } catch {
  }
}

function goBack() {
  router.push({name: 'MealSet'})
}
onMounted(() => {
  viewerName.value = localStorage.getItem('currentMealViewer') || ''
  fetchList();fetchListAdd()

})

// 可选：页面离开时清除
onUnmounted(() => {
  localStorage.removeItem('currentMealViewer')
})
</script>

<style scoped>
.meal-record-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 公共 filter-form 样式 */
.filter-form {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: #fff;
  flex-wrap: wrap;
  /* 移除分割线 */
  border-bottom: none;
  padding-left: 0;
}

/* 第一行和第二行之间的垂直间距 */
.first-line {
  margin-bottom: 4px;
}

/* 缩小两行间距 */
.second-line {
  margin-top: -15px;
}

/* 搜索框宽度 */
.keyword-item {
  width: 280px;
}

/* 把按钮推到最右 */
.second-line .action-buttons {
  margin-left: auto;
  margin-right: 16px;
}

/* 关键字输入框宽度 */
.keyword-item {
  width: 260px;
}
/* 让整个 wrapper 垂直排列 */
.meal-record-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.meal-table {
  flex: 1;
  margin-top: 5px;
}
.pagination-container {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}
.empty {
  text-align: center;
  color: #888;
  padding: 40px 0;
}
.viewer-tip {
  background: #f0f9eb;
  color: #67c23a;
  padding: 10px 16px;
  margin-bottom: 12px;
  font-size: 14px;
  border-left: 4px solid #67c23a;
}
/* ========== 页面整体布局 ========== */
.meal-record-wrapper {
  background-color: #fffefe;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}


/* ========== 搜索表单样式 ========== */
.filter-form {
  background-color: #ffffff;
  padding: 10px 0px;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.first-line {
  margin-bottom: 6px;
}

.second-line {
  margin-top: -12px;
}

.keyword-item {
  width: 260px;
  margin-left: 12px;
}

.second-line .action-buttons {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

/* ========== 空数据提示 ========== */
.empty {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 15px;
}

/* ========== 分页组件 ========== */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* ========== Dialog 优化 ========== */
.el-dialog__body {
  padding: 20px 30px;
}

.el-dialog__footer {
  text-align: right;
  padding: 10px 30px 20px;
}

.el-dialog__footer .el-button {
  min-width: 90px;
  margin-left: 12px;
}

</style>
